(function () {
    window.pageProductAll = [];
    function omesaasProduct(option) {
        if (!option.product || option.product instanceof Array) {
            return false;
        }
        window.pageProductAll.push(this);

        this.product = option.product;

        this.optionLength = option.product.options.length;

        this.params = {
            spu:this.product.spu,
            quantity: option.quantity || 1,
            price: option.product.variant_price_min,
            src: option.product.src,
            is_main_product: option.isMainProduct || false,
            block_id: option.block_id || "",
            productTitle: option.product.title,
            product_id: option.product.id
        };

        this.attrOption = []; //sku选项

        this.oldAttrOption = []; //老sku选项

        this.cartShake = true; //添加购物车提交限制

        this.buyShake = true; //立即购买提交限制

        this.wishlistShake = true;

        this.renderFirst = true; //初次渲染

        this.changeOption = option.changeOption; // 选择sku触发事件

        this.isMainProduct = option.isMainProduct || false; // 是否主商品

        this.block_id = option.block_id || new Date().getTime(); // 当前积木块id

        this.data_from = option.data_from || ""; //页面来源

        this.ec_currency_code = option.ec_currency_code || ""; //当前货币符号

        // this.handleRender = option.handleRender;
        this.variant = option.product.variants; // sku变体

        this.renderOption = option.renderOption || true; // 是否渲染规格

        this.wishlist = option.wishlist || ""; // 收藏按钮元素

        // if (option.product.variant instanceof Array) {
        //     this.variant = option.product.variant;
        // } else {
        //     this.variant = option.product.variants;
        // }

        // 是否渲染规格
        if (this.renderOption) {
            this.formDom = $(option.id);

            this.numberNode = this.formDom.find(".product-price-number");

            this.skuValueNode = $(".product-detail-skuspu .sku");

            this.marketNode = this.formDom.find(".product-price-market");

            this.discountNode = this.formDom.find(".product-price-discount");

            this.skuNode = this.formDom.find(".sku-cell");

            const tempID = `#omesaas-product-sku-${themeConfig.global.product_option_type || "default"}`;
            this.skuTemplate = $(tempID).html();

            const self = this;
            this.skuNode.on("click", ".product-sku-values-item", function (params) {
                self.renderFirst = false;
                const item = $(this).data("value");
                const index = $(this).data("index");
                // const idx = $(this).data("idx");
                // const item = self.attrOption[index - 1];
                // $(this).addClass("product-sku-values-item-active").siblings().removeClass("product-sku-values-item-active");

                //是否库存空能否购买
        
                // 如果是设置的不选中
                storeConfig.checked_first_sku = 2
                
                if(storeConfig.checked_first_sku == 2 && self.attrOption[index - 1].selected_value == item.value){
                    self.attrOption[index - 1].selected_value = "";
                    self.attrOption[index - 1].selected_value_label = "";
                    // // self.attrOption.length
                    // //清空下级选中的元素
                    // for (let i = 0; i < self.attrOption.length; i++) {
                    //    if(i>=index - 1){
                    //     self.attrOption[i].selected_value = "";
                    //     self.attrOption[i].selected_value_label = "";
                    //    }
                    // }
                }else{
                    self.attrOption[index - 1].selected_value = item.value;
                    self.attrOption[index - 1].selected_value_label = item.name;
                }

                


               

                for (let i = 0; i < self.optionLength; i++) {
                    self.attrOption[i].value = [];
                }
                self.setSkuOption();
                if(item.deleteItem) {
                    if($(this).hasClass('product-sku-values-item-active') && storeConfig.checked_first_sku == 2) {
                        self.attrOption[index - 1].selected_value = "";
                        self.attrOption[index - 1].selected_value_label = "";
                    }else {
                        self.attrOption[index - 1].selected_value = item.value;
                        self.attrOption[index - 1].selected_value_label = item.name;
                    }
                }
                
            });

            this.skuNode.on("change", ".product-sku-unselect", function (params) {
                self.renderFirst = false;
                const item = $(this).find("option:selected").data("value");
                const index = $(this).find("option:selected").data("index");

                if(storeConfig.checked_first_sku == 2){
                    $(this).siblings("svg").show();
                    $(this).siblings(".mo-edge").hide();
                }else{
                    $(this).siblings("svg").hide();
                    $(this).siblings(".mo-edge").show();
                }
                //是否库存空能否购买
                if (!self.isCurrentOptionBuy(item)) {
                    return false;
                }
                self.attrOption[index - 1].selected_value = item.value;
                for (let i = 0; i < self.optionLength; i++) {
                    self.attrOption[i].value = [];
                }
                self.setSkuOption();
            });
          
        }

        // 收藏操作
        if (this.wishlist) {
            this.wishlistEvent();
        }
        this.initSku();
    }

    omesaasProduct.prototype.event = function () {
        const self = this;
        this.skuNode.find(".product-sku-select-delete").click(function(event){
            event.stopPropagation();
            event.preventDefault();
            $(this).hide();
            $(this).siblings(".mo-edge").show();
            self.renderFirst = false;
            const select =  $(this).siblings(".product-sku-unselect");
            select.val(0);
            const index = $(this).data("index");
            self.attrOption[index - 1].selected_value = "";
            self.attrOption[index - 1].selected_value_label = "";
            for (let i = 0; i < self.optionLength; i++) {
                self.attrOption[i].value = [];
            }
            self.setSkuOption();
        })
    }

    omesaasProduct.prototype.initSku = function () {
        const self = this;
        const copyList = JSON.parse(JSON.stringify(this.variant));

        // 如果商品是单规格删除图片
        if(this.product.spec_mode === 1){
            copyList[0]['image'] = "";
        }

        // var minPriceItem = copyList.sort((a, b) => a.price - b.price);
        //查询第一个满足库存不为0的数据
        let FirstPriceItemIndex = 0;
        if (this.product.inventory_policy !== 2 && this.product.inventory_tracking === 1) {
            FirstPriceItemIndex = copyList.findIndex((el) => el.inventory_quantity > 0);
        }
        // const FirstPriceItemIndex = copyList.findIndex((el) => el.inventory_quantity > 0);

        const checkedSkuInfo = this.checkedSKu();

        if (this.optionLength ) {
            //多规款
            const selected = FirstPriceItemIndex === -1 ? false : this.isCurrentOptionBuy(copyList[FirstPriceItemIndex]);

            for (let i = 0; i < this.optionLength; i++) {
                var selected_value = "";
                var selected_value_label = "";

                    //默认选中
                    if (selected && storeConfig.checked_first_sku != 2) {
                        selected_value = copyList[FirstPriceItemIndex][`option${i + 1}_value`];
                        selected_value_label = copyList[FirstPriceItemIndex][`option${i + 1}_value_title`];
                    }
                    //如果有sku选中
                    if (checkedSkuInfo) {
                        selected_value = checkedSkuInfo[`option${i + 1}_value`];
                        selected_value_label = checkedSkuInfo[`option${i + 1}_value_title`];
                    }
                // }else{
                //     this.setPriceVal(copyList[0]);
                //  }

                this.attrOption.push({
                    name: "",
                    isImg: false,
                    selected_value_label: selected_value_label,
                    selected_value: selected_value,
                    value: []
                });
            }
            this.setSkuOption();
        } else {
            this.setSelectedVal(copyList[0]);
            this.setPriceVal(copyList[0]);
        }
    };

    //设置显示按钮
    //type: 'stockout' || 'delete',缺货 || 删除
    omesaasProduct.prototype.setButtonGroup = function (item,type = 'stockout') {
        if(type == 'delete') {
            this.formDom.find(".product-payment-box").hide();
            this.formDom.find(".product-cart-group").hide();
            this.formDom.find(".product-out-of-stock").hide()
            this.formDom.find(".product-out-of-delete").show();
            return false;
        }else {
            this.formDom.find(".product-out-of-delete").hide()
        }
        if (item.available && type == null) {
            this.formDom.find(".product-cart-group").show();
            this.formDom.find(".product-payment-box").show();
            this.formDom.find(".product-out-of-stock").hide();
        } else {
            if(storeConfig.product_put_off_control == 'buy') {
                this.formDom.find(".product-cart-group").show();
                this.formDom.find(".product-payment-box").show();
                this.formDom.find(".product-out-of-stock").hide();
            } else {
                this.formDom.find(".product-payment-box").hide();
                this.formDom.find(".product-cart-group").hide();
                this.formDom.find(".product-out-of-stock>div").text(lang.product.out_of_stock);
                this.formDom.find(".product-out-of-stock").show()
            }
        }
      
    };

    //获取当前sku属性
    omesaasProduct.prototype.checkedSKu = function (item) {
        const barcode = moi.getUrlParam("variant_barcode");
        const sku = moi.getUrlParam("variant_sku");
        const sku_code = moi.getUrlParam("variant_sku_code");

        if (barcode === "" && sku === "" && sku_code === "") {
            return false;
        }

        if (sku_code) {
            return this.variant.find(function (el) {
                return el.sku_code === sku_code;
            });
        }

        if (sku) {
            return this.variant.find(function (el) {
                return el.sku === sku;
            });
        }

        if (barcode) {
            return this.variant.find(function (el) {
                return el.barcode === barcode;
            });
        }
    };

    omesaasProduct.prototype.isCurrentOptionBuy = function (item) {
        // const quantity = item.quantity || item.inventory_quantity || 0;
        // if ((this.product.inventory_policy === 1 || this.product.inventory_policy === 3) && quantity === 0 && this.product.inventory_tracking === 1) {
        //     console.warn(this.product.inventory_policy);
        //     return false;
        // }
        return item.available ? true : false;
    };

    omesaasProduct.prototype.optionIndexKey = function (index) {
        return { title: `option${index + 1}_title`, value: `option${index + 1}_value_title`, id: `option${index + 1}_value` };
    };
    // 获取变体的颜色值
    omesaasProduct.prototype.getColorValue = function (name) {
        if (window.themeConfig && window.themeConfig.global.product_sku_style && window.themeConfig.global.product_sku_style == "color") {
            if (window._sku_color_ && window._sku_color_[name]) {
                return window._sku_color_[name];
            }
        }
        return name;
    };

    //获取可选项
    omesaasProduct.prototype.getOptional = function (sku) {
        for (let i = 0; i < sku.length; i++) {
            const element = sku[i];
            if (this.isCurrentOptionBuy(element)) {
                return element;
            }
        }
        return false;
    };

    omesaasProduct.prototype.setSkuOption = function () {
        let filterSKu = JSON.parse(JSON.stringify(this.variant));
        let options = [...this.product.options]
        let product_sku_options = [];
        let currentSkuItem = null
        if (themeConfig.global.product_sku_options) {
            product_sku_options = themeConfig.global.product_sku_options.map(function (item) {
                return item.toLowerCase();
            });
        }
        let isSetOptionImg = false;
       
        this.attrOption.map((attr,i) => {
            attr.optionsValue = options[i].values.map(k => k.option_value)
            const { title, value, id } = this.optionIndexKey(i);
            filterSKu.forEach((item) => {
                if (!attr.name) {
                    attr.name = item[title];
                    if (
                        product_sku_options &&
                        product_sku_options.indexOf(attr.name.toLowerCase()) > -1 &&
                        (!isSetOptionImg || themeConfig.global.product_sku_style === "color")
                    ) {
                        attr.isImg = true;
                        isSetOptionImg = true;
                    }
                }

                const currentIndex = attr.value.findIndex((val) => val.name === item[value]);
                if (currentIndex > -1) {
                    attr.value[currentIndex].quantity += item.inventory_quantity;
                    if (!attr.value[currentIndex].available && item.available) {
                        attr.value[currentIndex].available = item.available;
                    }
                } else {
                    attr.value.push({
                        name: item[value],
                        colorValue: this.getColorValue(item[value]),
                        value: item[id],
                        available: item.available,
                        deleteItem: item.deleteItem || false,
                        image: item.image || "",
                        quantity: item.inventory_quantity
                    });
                    attr.deleteSelect = ''
                }
            })
            //如果选择过滤选择的数据
            if (attr.selected_value) {
                const currentOption = attr.value.filter((el) => el.value === attr.selected_value);
                //如果没有匹配项；循环获取满足条件的第一条
                if (!currentOption.length) {
                    const option = this.getOptional(filterSKu);
                    attr.selected_value = option[id];
                    attr.selected_value_label = option[value];
                }

                filterSKu = filterSKu.filter((el) => el[id] === attr.selected_value);
                //如果没有信息清空信息
                if (!filterSKu.length) {
                    attr.selected_value = "";
                    attr.selected_value_label = "";
                    this.setSelectedVal(false);
                   currentSkuItem = {available: 1};
                }

                if (i === this.attrOption.length - 1 && filterSKu.length == 1 && attr.selected_value) {
                    this.setSelectedVal(filterSKu[0]);
                    this.setPriceVal(filterSKu[0]);
                    currentSkuItem = filterSKu[0];
                }
            } else {
                currentSkuItem = this.variant[0];
                this.setPriceVal(this.variant[0]);
                const newParams = Object.assign({}, this.params)
                newParams['image'] = this.product.image
                moi.onEvent("productOptionChange", newParams);
            }

            if(storeConfig.combination == 1) {
                if(attr.value.length != attr.optionsValue.length) {
                    attr.optionsValue.forEach((item,index) => {
                        let hasItem = attr.value.filter(i => i.name == item);
                        if(hasItem.length === 0) {
                            let hasThisSuk = this.product.variants.filter(imageItem => imageItem[value] == item);
                            attr.value.push({
                                name: item,
                                colorValue: item,
                                deleteItem: true,
                                available: 0,
                                value: hasThisSuk.length ? hasThisSuk[0][id] : new Date().getTime(),
                                image: hasThisSuk.length ? hasThisSuk[0].image : {src: ''}
                            });
                        }
                    })
                    //实现排序一致
                    attr.value = attr.value.sort((a,b) => {
                        return attr.optionsValue.indexOf(a.name) - attr.optionsValue.indexOf(b.name);
                    })
                }
            }
            
            return attr
        })
        
        this.render(currentSkuItem);
    };

    //设置价格
    omesaasProduct.prototype.setPriceVal = function (currentSku) {
        //多款式商品价格展示
        let product_price_display = window.themeConfig.global.product_price_display || 0;
        let price = 0;
        let comparePrice = 0;
        
        if (this.renderOption) {
            if(storeConfig.checked_first_sku == 2 && this.renderFirst) {
                if(product_price_display == 0) {
                    price = currentSku.price
                    comparePrice = currentSku.compare_at_price
                }else if(product_price_display == 1) {
                    price = this.product.variant_price_min
                    comparePrice = this.product.variant_compare_at_price_min
                }else if(product_price_display == 2) {
                    price = this.product.variant_price_max
                    comparePrice = this.product.variant_compare_at_price_max
                }else {
                    price = this.product.variant_price_min
                    comparePrice = this.product.variant_price_max
                }
                if(product_price_display == 3) {
                    let text = price < comparePrice ?  `${formatMoney(price, oemcart_currency)} - ${formatMoney(comparePrice, oemcart_currency)}` : `${formatMoney(price, oemcart_currency)}`;
                    this.numberNode.html(text);
                }else {
                    this.numberNode.html(formatMoney(price, oemcart_currency));
                }
            }else {
                price = currentSku.price
                comparePrice = currentSku.compare_at_price
                this.numberNode.html(formatMoney(price, oemcart_currency));
            }
            
            
            
            this.skuValueNode.html(currentSku.sku);
            
            if (parseFloat(comparePrice) > parseFloat(price)) {
                if(storeConfig.checked_first_sku == 2 && this.renderFirst) {
                    
                    if(product_price_display == 3) {
                        this.marketNode.html("");
                    }else {
                        this.marketNode.html(formatMoney(comparePrice, oemcart_currency));
                    }
                }else {
                    this.marketNode.html(formatMoney(comparePrice, oemcart_currency));
                }

                if (window.themeConfig.global.product_discount_label_style_switch) {
                    let disPrice = 0;
                    let disComparePrice = 0;
                    if(storeConfig.checked_first_sku == 2 && this.renderFirst && product_price_display == 3) {
                        disPrice = this.product.variant_price_min
                        disComparePrice = this.product.variant_compare_at_price_min
                    }else {
                        disPrice = price
                        disComparePrice = comparePrice
                    }

                    if(disComparePrice == 0) {
                        this.marketNode.html("");
                        this.discountNode.hide();
                        return
                    } 

                    // 设置折扣价格
                    if (window.themeConfig.global.product_discount_label_style == 2) {
                        
                        this.discountNode.html(
                            lang.general.save +
                                " " +
                                Math.floor((1 - parseFloat(disPrice) / parseFloat(disComparePrice)) * 100) +
                                "%"
                        );
                    } else {
                        this.discountNode.html(
                            lang.general.save +
                                " " +
                                formatMoney(
                                    (parseFloat(disComparePrice) - parseFloat(disPrice)).toFixed(2),
                                    oemcart_currency
                                )
                        );
                    }

                    this.discountNode.show();
                }
            } else {
                this.marketNode.html("");
                this.discountNode.hide();
            }
        }
    };

    //设置选中的val
    omesaasProduct.prototype.setSelectedVal = function (currentSku) {
        const product = this.product;
        const params = this.params;
        if (!currentSku) {
            this.params = {
                src: product.src,
                productTitle: product.title,
                product_id: product.id,
                sku_value: "",
                quantity: params.quantity || 1
            };
        } else {
            this.params = Object.assign(params, currentSku);
            //设置选中的sku
            if (this.optionLength && this.params.sku) {
                let skuName = [];
                for (let i = 0; i < this.optionLength; i++) {
                    const title = this.params[`option${i + 1}_title`];
                    const value = this.params[`option${i + 1}_value_title`];
                    skuName.push(`${title}:${value}`);
                }
                this.params["sku_value"] = skuName.join("<br/>");
            }
        }

        //设置url 链接
        if (location.pathname.indexOf("/products") !== -1 && this.params.sku_code && this.isMainProduct && !this.renderFirst) {
            history.replaceState(null, null, moi.setUrlParams(location.href, { variant_sku_code: this.params.sku_code }));
        }

        //如果是主商品存入主商品选中数据
        if (this.isMainProduct) {
            $(".mo-editor-reset")
                .find("img")
                .each(function (index, element) {
                    $(this).attr("referrer", "no-referrer");
                });
            moi.setPageStorage("mian_product_params", this.params);
            // ppec 验证
            if (this.product.status === 0 && moi.getUrlParam('preview')) {
                moi.addEvent('payVerified', function (event) {
                    event.stopPropagation();
                    event.params["code"] = 400;
                    moi.alertInfo({ content: "当前为预览链接不可操作" });
                });
            }
        }
        moi.onEvent("productOptionChange", this.params);
        //设置当前积木块相关的选中商品数据
        moi.setPageStorage("product_params" + this.block_id, this.params);
        this.changeOption && this.changeOption.call(this, this.params);
    };

    omesaasProduct.prototype.optionCompare = function (html,currentSkuItem) {
        const skuNode = $(`<div>${html}</div>`);
        if (this.oldAttrOption.length) {
            this.attrOption.forEach((item, index) => {
                if (item.selected_value !== this.oldAttrOption[index].selected_value) {
                    const valIndex = item.value.findIndex((val) => val.value === item.selected_value);
                    if (valIndex > -1) {
                        const currentNode = this.skuNode
                            .find(".moi-product-sku-value")
                            .eq(index)
                            .find(".product-sku-values-item")
                            .eq(valIndex);
                        const labelNode = this.skuNode.find(".moi-product-sku-label").eq(index);
                        currentNode.addClass("product-sku-values-item-active").siblings().removeClass("product-sku-values-item-active");
                        labelNode.html(skuNode.find(".moi-product-sku-label").eq(index).html());
                    }
                    // 或者selected_value为空
                    if(item.selected_value == ""){
                        this.skuNode
                            .find(".moi-product-sku-value")
                            .eq(index)
                            .find(".product-sku-values-item").removeClass("product-sku-values-item-active")
                    }
                }

                var availabIsEqual =
                    item.value.map((el) => el.available).toString() != this.oldAttrOption[index].value.map((el) => el.available).toString();
                var itemIsEqual =
                    item.value.map((el) => el.value).toString() !== this.oldAttrOption[index].value.map((el) => el.value).toString();
                //判断选项和是否可购买是否一样 
                if (itemIsEqual || availabIsEqual) {
                    this.skuNode.find(".moi-product-sku-value").eq(index).html(skuNode.find(".moi-product-sku-value").eq(index).html());
                }
            });
        } else {
            this.skuNode.html(html);
            this.event();
        }

        if(currentSkuItem) {
            let can_buy = true
            let showBtnType = 'stockout'
            
            this.skuNode.find('.product-sku-values-item-disable').each((elemIndex,elem) => {
                if(!can_buy) return
                if($(elem).hasClass('product-sku-values-item-active')) {
                    if($(elem).attr('is_deleteProduct') == 'true') {
                        showBtnType = 'delete'
                    }else {
                        showBtnType = 'stockout'
                    }
                    can_buy = false;
                }
            })
            if (!can_buy) {
                this.setButtonGroup(currentSkuItem,showBtnType)
            }else {
                this.setButtonGroup(currentSkuItem,null)
            }

        }

        this.oldAttrOption = JSON.parse(JSON.stringify(this.attrOption));
    };

    // 渲染页面
    omesaasProduct.prototype.render = function (currentSkuItem) {
        if (this.renderOption) {
            // this.oldAttrOption = this.attrOption;
            const self = this;
            engine
                .parseAndRender(this.skuTemplate, {
                    skus: this.attrOption,
                    lang:lang,
                    checkedFirstSku:storeConfig.checked_first_sku,
                    productSkuStyle: themeConfig.global.product_sku_style || "image_text",
                    productSkuSize: "sku-image-item-" + themeConfig.global.product_sku_size || "mall"
                })
                .then(function (liquidHtml) {
                    self.optionCompare(liquidHtml,currentSkuItem);
                    // window.addLazyImages && addLazyImages(self.skuNode.find("img[data-src]"));
                });
        }
        if (!this.product.available) {
            this.setSelectedVal({ quantity: this.params.quantity });
            this.discountNode.hide();
        }
    };

    //验证数据
    omesaasProduct.prototype.verifyOption = function (type) {
        //库存为0时不能购买
        if (this.product.available === 0) {
            moi.alertInfo({ content: "quantity empty" });
            return false;
        }

        // TODO 未上架的商品不可购买
        if (this.product.status === 0 && moi.getUrlParam('preview')) {
            moi.alertInfo({ content: "当前为预览链接不可操作" });
            return false;
        }

        if (type === "cart" && !this.cartShake) {
            return false;
        }

        if (type === "buy" && !this.buyShake) {
            return false;
        }
        for (let i = 0; i < this.attrOption.length; i++) {
            if (!this.attrOption[i].selected_value) {
                $("html, body").animate({ scrollTop: this.skuNode.find(".product-sku-name").eq(i).offset().top-200 });
                moi.tooltip({
                    placement: "right",
                    el: this.skuNode.find(".product-sku-name").eq(i),
                    content: lang.product.please_select_sku.replace('{sku}',this.product.options[i].name)
                });
                return false;
            }
        }
        return true;
    };

    //获取ec_data参数
    omesaasProduct.prototype.getEcData = function () {
        const self = this;
        return {
            ec_data_id: self.product.id,
            ec_data_from: self.data_from,
            ec_data_name: encodeURIComponent(self.product.title),
            ec_data_price: self.params.price,
            ec_data_discount_price: self.params.price,
            ec_data_spu: self.product.spu,
            ec_data_image: self.product.src,
            ec_data_category: self.product.product_type,
            ec_data_uniq_id: self.product.id,
            ec_data_sku: self.params.sku,
            ec_data_sku_code: self.params.sku_code,
            ec_data_quantity: self.params.quantity,
            ec_data_sku_name: self.params.sku_value || "",
            ec_currency_code: self.ec_currency_code,
            ec_data_action_type: ""
        };
    };

    omesaasProduct.prototype.share = function (platform) {
        const self = this;
        const ec_data = {
            ec_data_id: self.product.id,
            ec_data_from: self.data_from,
            ec_data_name: encodeURIComponent(self.product.title),
            ec_data_price: self.product.variant.price,
            ec_data_discount_price: self.product.variant.price,
            ec_data_spu: self.product.spu,
            ec_data_image: self.product.src,
            ec_data_category: self.product.product_type,
            ec_data_uniq_id: self.product.id,
            ec_data_sku: self.product.variant.sku,
            ec_data_sku_code: self.product.variant.sku_code,
            ec_data_quantity: 1,
            ec_data_sku_name: self.product.variant.sku_value,
            ec_currency_code: self.ec_currency_code,
            ec_data_action_type: ""
        };
        ec_data.ec_data_action_type = "share_product";
        callback_share_product(ec_data, platform);
    };

    //回调添加购物车
    omesaasProduct.prototype.callbackAddToCart = function () {
        const self = this;
        const ec_data = self.getEcData();
        ec_data.ec_data_action_type = "add_to_cart";
        callback_add_to_cart(ec_data);
    };


    // 自定义属性内容组装
    omesaasProduct.prototype.getCustomAttr = function (attr) {
        return attr.filter(el=>el.params).map(el=>{
            let params = el.params
            let value = '';
            if(["checkbox","image_group","block_text","image"].includes(el.type)){
                    value = params.map(param=>{
                        const current = el.rule.selected.find(select=>select.name == param.value);
                        return {
                            value:current.name,
                            price:current.price || 0,
                            urls:param.url || current.other || ""
                        }
                    })
            }else{
                value = params.value;
            }
            
            return {
                type:el.type,
                value:value,
                name:el.title,
                price:el.price,
                urls:el.type === "file"?params.url:'',
            }
        })
    }

    //加入购物车
    omesaasProduct.prototype.addCart = function (complete, success) {
        const self = this;
        self.cartShake = false;
        let ret = moi.onEvent("payVerified", { property: [],custom_attr:[], product: this.params, code: 200 });
        if (ret.params.code === 200) {
            self.params["property"] = ret.params.property;
           
          

            moi.ajax({
                url: "/cart/add",
                type: "post",
                data: JSON.stringify({
                    // TODO 删除参数
                    // ...self.params,
                    product_id: this.product.id,
                    sku_code: this.params.sku_code,
                    quantity: this.params.quantity,
                    data_from: self.data_from,
                    property: ret.params.property
                }),
                complete() {
                    self.cartShake = true;
                },
                success: function (data) {

                    // 如果存在自定义属性详细数据 组装成可显示的自定义数据
                    if(ret.params.original){
                        self.params['custom_attr'] = data.data.items[data.data.items.length - 1].property
                    }

                    complete && complete.call(this);
                    if (!data.code) {

                        moi.onEvent("cartChange", data.data);

                        self.product['cart'] = data.data;
                        moi.onEvent("addToCart", self.product);
                        if (window.callback_add_to_cart) {
                            self.callbackAddToCart();
                        }
                        moi.changeCartNumber(data.data.item_count);
                        miniCart();
                        self.setSelectedVal({ subtotalPrice: data.data.items_subtotal_price });
                    }
                    success && success.call(self, data);
                }
            });
        } else {
            self.cartShake = true;
            complete && complete.call(this);
        }
    };

    //立即购买
    omesaasProduct.prototype.buynow = function (complete, success) {
        const self = this;
        self.buyShake = false;
        let ret = moi.onEvent("payVerified", { property: [], product: this.params, code: 200 });
        if (ret.params.code === 200) {
            self.params["property"] = ret.params.property;
            moi.ajax({
                url: "/cart/buynow",
                type: "post",
                data: JSON.stringify({
                    product_id: this.product.id,
                    sku_code: this.params.sku_code,
                    quantity: this.params.quantity,
                    data_from: self.data_from,
                    property: ret.params.property
                }),
                complete() {
                    self.buyShake = true;
                },
                success: function (ret) {
                    complete && complete.call(this);

                    if(ret.data.code == -1000){
                        alert(ret.data.msg);
                        return
                    }
                    if (!ret.code) {
                        moi.onEvent("buynow", self.product);

                        if (!ret.code && window.callback_add_to_cart) {
                            self.callbackAddToCart();
                        }
                        if (ret.data.checkout_url && moi) {
                            ret.data.checkout_url = moi.setUrlParams(ret.data.checkout_url, { _ref: location.href });
                        }
                    }
                    success && success.call(self, ret);
                }
            });
        } else {
            self.buyShake = true;
            complete && complete.call(this);
        }
    };

   

    //购物车弹窗
    omesaasProduct.prototype.cartLayer = function () {

        // 处理加购更具设置跳转 1 默认弹出 2 成功提示 3侧边 4购物车
        if(storeConfig.purchase_style == 2){
            moi.alertInfo({content:lang.product.add_cart_succeed,placement:"top",type:"success"})
            return
        }
        if(storeConfig.purchase_style == 3){
            showMiniCart()
            return
        }

        if(storeConfig.purchase_style == 4){
            location.href = '/cart'
            return
        }

        
        const option = JSON.parse(JSON.stringify(this.params));
        let isProperty = false; //是否支持自定义
        if (option.property && option.property.length) {
            isProperty = option.property.some((el) => typeof el.params !== "string");
        }
        const subtotalPrice = formatMoney(parseFloat(option.subtotalPrice || 0), oemcart_currency);
        const popupLayer = moi.popup();
        engine
            .parseAndRender($("#omesaas-popup-addPurchase-success").html(), {
                option: option,
                subtotalPrice: subtotalPrice,
                isProperty: isProperty,
                storeConfig:storeConfig,
                lang: window.lang
            })
            .then(function (html) {
                popupLayer.addContent(html);
                const temp = popupLayer.temp;
                //提交购物车跳转地址填写
                const submitNodes = temp.find(".cart-buyNow");

                submitNodes.on("click", function () {
                    temp.find(".cart_form").submit();
                    popupLayer.close();
                });
            });
    };

    /**
     * 
     * @param {*} isUpdate 是否采用新写法，用于兼容以前的模板，之后会采用新写法
     * @param {*} parentsClass 图片列表的外层父元素类名
     * @param {*} defaultImgClass 更新的图片类名
     */
    omesaasProduct.prototype.renderProductImgList = function (params = {}) {
        let config = {
            isUpdate: false, 
            parentsClass: '.collection_item',
            defaultImgClass :'.default_img',
            ...params
        }
        $(".block_product_img_list.noRender").each((index, elem) => {
            let width = $(elem).width() - $(elem).width() * 0.26;
            let renderMaxLength = Math.floor(width / 28);

            let listDom = $(elem).find(".img_list .img_list_item");
            let listDomLen = listDom.length > renderMaxLength ? "+" + (listDom.length - renderMaxLength) : "";
            $(elem).find(".img_list .morNumber").text(listDomLen);
            listDom.each((itemIndex, listItem) => {
                if (itemIndex >= renderMaxLength) {
                    $(listItem).remove();
                }
            });
            $(elem).removeClass("noRender");
            listDom.on("mouseenter", function () {
                let src = $(this).find("img").attr("src").split("?")[0];
                var defaultImgNode =  config.isUpdate ? $(this).parents(config.parentsClass).find(config.defaultImgClass) : $(this).parent().parent().parent().find(".default_img");
                defaultImgNode.attr("data-src", src);
                window.lazyLoadImage(defaultImgNode);
                $(this).addClass("active").siblings().removeClass("active");
            });
        });
    };


    omesaasProduct.prototype.wishlistParams = function (value,hit_type_category) {
        var ec_data = this.getEcData();
        ec_data.ec_data_action_type = "view_content";
        ec_data.ec_data_from = "wishlist";
        function getMetaContent(metaName){
            const metas = document.getElementsByTagName("meta");
            for (let i = 0; i < metas.length; i++) {
                if (metas[i].getAttribute("name") === metaName) {
                    return metas[i].getAttribute("content");
                }
            }
            return "";
        }
        const collectParams = {
            "hit_type_category": hit_type_category,
            "hit_type_name": "wish_product",
            "hit_type_lable": "product",
            ec_data:ec_data,
            hit_type:"event",
            hit_type_value:value,
            pv_id: window.oemcart_pv_id || "",
            store_id: window.oemcart_store_id || "",
            document_location_url: encodeURIComponent(window.location.href),
            document_location_title: document.title,
            meta_keywords: getMetaContent("keywords"),
            prev_url: document.referrer,
            vid: window.oemcart_global_unique_id || "",
            rnd: Math.random()
        };
        return collectParams
    }

    // 商品收藏
    omesaasProduct.prototype.wishlistEvent = function () {
        var wishlistNode = $(this.wishlist);
        var that = this;
      
       
        if(that.wishlistShake){
            this.wishlistShake = false;
            wishlistNode.click(function () {
                $(this).find(".wishlist-animated").addClass("animated tada");
                setTimeout(()=>{
                   $(this).find(".wishlist-animated").removeClass("animated tada");
                },700)
                // 未登录跳转登录页面
                if (!oemcart_user_id) {
                    location.href = "/account/login?checkout_url=" + encodeURIComponent(location.href);
                    return;
                }
                if (that.product.in_wishlist == 1) {
                    that.product.in_wishlist = 0;
                    wishlistNode.removeClass("product-wishlist-active");
                    moi.ajax({
                        url: "/wishlist",
                        type: "DELETE",
                        data: JSON.stringify({
                            product_id: that.product.id,
                            event:that.wishlistParams(0,"remove_from_wishlist")
                        }),
                        complete() {
                            that.wishlistShake = true;
                        },
                        success: function (ret) {
                            if (!ret.code) {
                                moi.alertInfo({content:lang.product.remove_from_wishlist,type:"success",placement:"top"})

                            }else{
                                moi.alert({ title: ret.msg });

                            }
                        }
                    });
                } else {
                    that.product.in_wishlist = 1;
                    wishlistNode.addClass("product-wishlist-active ");
                    moi.ajax({
                        url: "/wishlist",
                        type: "POST",
                        data: JSON.stringify({
                            product_id: that.product.id,
                            event:that.wishlistParams(1,"add_to_wishlist")
                        }),
                        complete() {
                            that.wishlistShake = true;
                        },
                        success: function (ret) {
                            if (!ret.code) {
                                moi.alertInfo({content:lang.product.add_to_wishlist,type:"success",placement:"top"})
                                callback_add_to_wishlist && callback_add_to_wishlist(that.getEcData());
                            } else {
                                moi.alert({ title: ret.msg });
                            }
                        }
                    });
                    // 收藏事件回传
                }
            });
        }
       
    };

    window.omesaasProduct = omesaasProduct;
})();
